<?php

namespace app\admin\controller;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Admin;
use app\common\model\Area;
use app\common\model\shop\Data;
use app\common\model\User;
use PDOException;
use think\Config;
use think\Db;
use think\exception\ValidateException;

/**
 * 门店管理
 *
 * @icon fa fa-user
 */
class Shop extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['dashboard'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $group_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->group_id = $this->auth->getGroupIds()[0];
        $this->view->assign('group_id', $this->auth->getGroupIds()[0]);
        $this->assignconfig('city_lists', Admin::whereIn('id', AuthGroupAccess::where('group_id', 2)->column('uid'))->column('id,nickname'));
        $this->assignconfig('county_lists', Admin::whereIn('id', AuthGroupAccess::where('group_id', 5)->column('uid'))->column('id,nickname'));
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->group_id == 2) {
                $admin = $this->auth->getUserInfo();
                $ids = Area::where('pid', $admin['region_id'])->column('id');
                $admin = new Admin;
                foreach ($ids as $v) {
                    $admin->whereOr("FIND_IN_SET({$v},region_id)");
                }
                $admin_ids = $admin->column('id');
                array_push($admin_ids, $this->auth->id);
                $this->model->whereIn('company_id', $admin_ids);
            }
            if ($this->group_id == 5) {
                $this->model->where('company_id', $this->auth->id);
            }
            $this->model->where('role', 'shop');
            $list = $this->model
            ->with(['category', 'county'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->rank = ($list->currentPage() - 1) * $list->listRows() + $k + 1;
//                $fee_order = \app\common\model\FeeOrder::where(['user_id' => $v['id'], 'is_pay' => 1])->find();
                $v->order = \app\common\model\FeeOrder::where(['user_id' => $v['id'], 'is_pay' => 1])->find();
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $factory_item = Config::get('site.shop_item');
            $fee_items = [];
            foreach ($factory_item as $key => $item) {
                $fee_items[] = [
                    'item'  => $key,
                    'amount'=> ''
                ];
            }

            $this->view->assign('fee_items', json_encode($fee_items));

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $user = \app\common\model\User::where(['username' => $params['username']])->find();
        if ($user) {
            $this->error('该账号名已存在');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.shop' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['role'] = 'shop';
            // if ($this->group_id != 1) {
            //     $params['company_id'] = $this->auth->id;
            // }
            $factory_ids = $params['factory_id'];
            unset($params['factory_id']);
            $result = $this->model->allowField(true)->save($params);
            if ($result) {
                $factory_data = explode(',', $factory_ids);
                $array = [];
                foreach ($factory_data as &$v) {
                    $user = User::get($v);
                    array_push($array, [
                        'shop_id' => $this->model->id,
                        'factory_id' => $v,
                        'category_id' => $user->category_id,
                    ]);
                }
                $data = new Data();
                Data::where('shop_id', $this->model->id)->delete();
                $data->allowField(true)->saveAll($array);
            }

            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            # - 判断是否json字符串
            $items = json_decode($row->fee_items, true) ?: [];

            $factory_item = Config::get('site.shop_item');
            $fee_items = [];
            foreach ($factory_item as $key => $val) {
                $item = [ 'item' => $key, 'amount' => 0 ];
                foreach ($items as $v) {
                    if ($key == $v['item']) {
                        $item['amount'] = $v['amount'];
                    }
                }
                $fee_items[] = $item;
            }

            $this->view->assign('fee_items', json_encode($fee_items));
            $factory_ids = Data::where('shop_id', $row->id)->column('factory_id');
            $this->view->assign('factory_ids', implode(',', $factory_ids));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $user = \app\common\model\User::where(['username' => $params['username'], 'id' => ['neq', $row->id]])->find();
        if ($user) {
            $this->error('该账号名已存在');
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.shop' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['role'] = 'shop';
          
            $factory_ids = $params['factory_id'];
            unset($params['factory_id']);
            $result = $row->allowField(true)->save($params);
            // dd($params);
            // if ($result) {
                $factory_data = explode(',', $factory_ids);
                $array = [];
                foreach ($factory_data as &$v) {
                    $user = User::get($v);
                    array_push($array, [
                        'shop_id' => $row->id,
                        'factory_id' => $v,
                        'category_id' => $user->category_id,
                    ]);
                }

                $data = new Data();
                Data::where('shop_id', $row->id)->delete();
                $data->allowField(true)->saveAll($array);
            // }

            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 查看
     */
    public function dashboard()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->group_id == 2) {
                $admin = $this->auth->getUserInfo();
                $ids = Area::where('pid', $admin['region_id'])->column('id');
                $admin = new Admin;
                foreach ($ids as $v) {
                    $admin->whereOr("FIND_IN_SET({$v},region_id)");
                }
                $admin_ids = $admin->column('id');
                array_push($admin_ids, $this->auth->id);
                $this->model->whereIn('company_id', $admin_ids);
            }
            if ($this->group_id == 5) {
                $this->model->where('company_id', $this->auth->id);
            }
            $this->model->where('role', 'shop');
            $list = $this->model
                ->with(['category', 'county'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->rank = ($list->currentPage() - 1) * $list->listRows() + $k + 1;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function select()
    {
        $list = $this->model->where('role', 'shop')->order('id ASC')->select();
        $data = [];
        foreach ($list as $v) {
            $data[$v['id']] = $v['nickname'];
        }
        return json($data);
    }
}
